package fr.snac.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.util.DisplayMetrics;
import android.widget.ImageView;

import com.tumblr.jumblr.types.PhotoSize;

public class PhotoUtil {

	public static PhotoSize getMoreAdaptedPhoto(List<PhotoSize> sizes, DisplayMetrics metrics){

		int height = metrics.heightPixels;
		int difference = -1;

		PhotoSize photo = null;

		for (PhotoSize ps : sizes){
			int photoHeight = ps.getHeight();

			if (photoHeight < height){
				int tmpDifference = height - photoHeight;

				if (tmpDifference < difference || difference == -1){
					photo = ps;
					difference = tmpDifference;
				}
			}
		}

		return photo;
	}

	public static boolean saveBitmapImage(Bitmap image, String imageName){

		File imagesFolder = new File(FilesUtil.getImageFolderPath());

		if (imagesFolder != null){

			String fileName = imageName + ".png";
			File img = new File(imagesFolder, fileName);

			FileOutputStream fos;

			try {
				fos = new FileOutputStream(img);
				image.compress(Bitmap.CompressFormat.PNG, 50, fos);
				fos.flush();
				fos.close();
			} catch (IOException e) {
				return false;
			}			
		}

		return true;
	}

	public static Bitmap getBitmapFromImageView(ImageView imageView){

		BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
        Bitmap bitmap = bitmapDrawable.getBitmap();
		
		return bitmap;
	}
	
	public static String getPhotoOrientation(PhotoSize photo){
		
		if (photo.getHeight() >= photo.getWidth()) return Constants.PHOTO_ORIENTATION_PORTRAIT;
		else return Constants.PHOTO_ORIENTATION_LANDSCAPE;
	}

}
